//package com.example.testdemo.config;
//
//import com.mongodb.MongoClient;
//import com.mongodb.MongoClientOptions;
//import com.mongodb.MongoCredential;
//import com.mongodb.ServerAddress;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.data.mongodb.MongoDbFactory;
//import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
//
//import java.util.ArrayList;
//import java.util.List;
//
//@Configuration
//@EnableConfigurationProperties(MongoSettingsProperties.class)
//public class MongoConfig {
//
//    // 注入配置实体
//    @Autowired
//    private MongoSettingsProperties mongoSettingsProperties;
//
//    // 覆盖默认的MongoDbFactory
//    @Bean
//    MongoDbFactory mongoDbFactory() throws Exception {
//        //客户端配置（连接数、副本集群验证）
//        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
//        builder.connectionsPerHost(mongoSettingsProperties.getConnectionsPerHost());
//        builder.minConnectionsPerHost(mongoSettingsProperties.getMinConnectionsPerHost());
//        if (mongoSettingsProperties.getReplicaSet() != null) {
//            builder.requiredReplicaSetName(mongoSettingsProperties.getReplicaSet());
//        }
//        MongoClientOptions mongoClientOptions = builder.build();
//
//        // MongoDB地址列表
//        List<ServerAddress> serverAddresses = new ArrayList<>();
//        for (String address : mongoSettingsProperties.getAddress()) {
//            String[] addressSplit = address.split(":");
//            String host = addressSplit[0];
//            Integer port = Integer.valueOf(addressSplit[1]);
//
//            ServerAddress serverAddress = new ServerAddress(host, port);
//            serverAddresses.add(serverAddress);
//        }
//        // 连接认证
//        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(
//                mongoSettingsProperties.getUsername(),
//                mongoSettingsProperties.getAuthenticationDatabase() != null ? mongoSettingsProperties.getAuthenticationDatabase() : mongoSettingsProperties.getDatabase(),
//                mongoSettingsProperties.getEncryption() ? RSAUtils.decrypt(mongoSettingsProperties.getPublicKey() , mongoSettingsProperties.getPassword()).toCharArray() : mongoSettingsProperties.getPassword().toCharArray());
//
//        //创建客户端和Factory
//        MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, mongoClientOptions);
//        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, mongoSettingsProperties.getDatabase());
//
//        return mongoDbFactory;
//    }
//
//}
